<template>
  <el-dialog
    :title="propertyList.id?'编辑房产':'添加房产'"
    :visible="isShowDislog"
    :close-on-click-modal="false"
    :destroy-on-close="true"
    @close="isCancel"
  >
    <el-form ref="from" label-width="100px" :model="propertyList" :rules="rules">
      <el-form-item label="经纪">
        <el-select v-model="propertyList.agent.id" placeholder="请选择">
          <el-option
            v-for="agents in agentsList"
            :key="agents.id"
            :label="agents.name"
            :value="agents.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="分类">
        <el-select v-model="propertyList.category.id" placeholder="请选择">
          <el-option
            v-for="category in categoriesList"
            :key="category.id"
            :label="category.title"
            :value="category.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="标题" prop="title">
        <el-input v-model="propertyList.title" placeholder="请输入标题" />
      </el-form-item>
      <el-form-item label="标签">
        <el-tag
          v-for="(tag,index) in propertyList.tags"
          :key="index"
          type="success"
          closable
          @close="handleClose(tag)"
        >{{ tag }}
        </el-tag>
        <el-input
          v-if="inputVisible"
          ref="saveTagInput"
          v-model="tagValue"
          class="input-new-tag"
          size="small"
          @blur="handleInputConfirm"
        />
        <!-- @keyup.enter.native="handleInputConfirm" -->
        <el-button v-else class="button-new-tag" size="small" @click="showInput">+ New Tag</el-button>
      </el-form-item>
      <el-form-item label="地址">
        <el-row type="flex">
          <el-col :span="7">
            <el-cascader
              v-model="map"
              :options="mapList"
              :props="{ expandTrigger: 'hover',value:'name',label:'name' }"
              @change="handleChange"
            />
          </el-col>
          <el-col>
            <el-input v-model="propertyList.address" disabled />
          </el-col>

        </el-row>

      </el-form-item>
      <el-form-item label="价格">
        <el-input v-model="propertyList.price" placeholder="请输入价格" />
      </el-form-item>
      <el-form-item label="描述" prop="desc">
        <el-input
          v-model="propertyList.desc"
          type="textarea"
          :rows="3"
          placeholder="请输入描述"
        />
      </el-form-item>
      <el-form-item label="内容">
        <template>
          <vue-editor v-model="propertyList.content" />
        </template>
      </el-form-item>
      <el-form-item label="封面">
        <template>
          <ImagesUpload ref="coverImage" />
        </template>
      </el-form-item>
      <el-form-item label="介绍图片">
        <template>
          <ImagesUpload ref="photoImage" :show-iamges="false" />
        </template>
      </el-form-item>

    </el-form>
    <template slot="footer">
      <el-button type="danger" size="small" @click="isCancel">取消</el-button>
      <el-button type="primary" size="small" @click="isOK">确定</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { map } from '@/api/map'
import { getPropertyApi, editPropertiesApi, addPropertiesApi } from '@/api/property'
import { VueEditor } from 'vue2-editor'
import ImagesUpload from '@/components/ImagesUpload'
export default {
  components: { VueEditor, ImagesUpload },
  props: {
    isShowDislog: {
      type: Boolean,
      default: false
    },
    categoriesList: {
      type: Array,
      require: true,
      // eslint-disable-next-line vue/require-valid-default-prop
      default: []
    },
    agentsList: {
      type: Array,
      require: true,
      // eslint-disable-next-line vue/require-valid-default-prop
      default: []
    }
  },
  data() {
    return {
      repOk: true,
      agentsId: '',
      categoryId: '',
      inputVisible: false,
      tagValue: '',
      addressList: [],
      propertyList: {
        agent: {},
        category: {},
        title: '',
        tags: [],
        address: '',
        price: '',
        desc: '',
        content: '',
        image: '',
        photos: []
      },
      mapList: [],
      map: '',
      rules: {
        title: [{ required: true, message: '标题不能为空', trigger: 'blur' }],
        desc: [{ required: true, message: '描述不能为空', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getMap()
  },
  methods: {
    // 地址改变时触发
    handleChange(val) {
      console.log(val)
      // this.map = val.join(',')
      this.propertyList.address = val.join(',')
      this.map = []
    },
    // 获取全国地区
    async getMap() {
      const res = await map()
      // console.log(res.districts[0].districts)
      this.mapList = res.districts[0].districts

      // 改造数据
      this.mapList = this.remouldMap(this.mapList)
    },
    // 递归改造数据
    remouldMap(arr) {
      arr.forEach(item => {
        // console.log(item)
        item.children = item.districts
        this.remouldMap(item.districts)
        if (item.districts.length === 0) {
          delete item.children
        }
      })
      // console.log(arr)
      return arr
    },
    // 确定
    async isOK() {
      // console.log(this.$refs.photoImage.fileList)
      await this.$refs.from.validate()

      let isCover = true
      let isPhoto = true
      const coverfileList = this.$refs.coverImage.fileList
      isCover = coverfileList.every(item => item.status === 'success')

      this.propertyList.image = coverfileList[0] ? coverfileList[0].url : ''
      this.propertyList.photos = []
      this.$refs.photoImage.fileList.forEach((item) => {
        this.propertyList.photos.push(item.url)
        isPhoto = item.status === 'success'
      })
      if (!this.propertyList.image) {
        this.$message.warning('请先上传封面')
        return
      }
      // console.log('--1--', isCover)
      // console.log('--2--', isPhoto)
      if (!isCover || !isPhoto) {
        this.$message.warning('请先等图片上传完成')
        return
      }
      this.repOk = false

      // console.log(this.propertyList)
      if (this.propertyList.id) {
        const res = await editPropertiesApi(this.propertyList)
        console.log(res)
        this.$message.success('编辑成功')
      } else {
        await addPropertiesApi(this.propertyList)
        this.$message.success('新增成功')
      }

      this.$parent.editing()
      this.$parent.isShowDislog = false
      this.repOk = true
    },
    // 根据id获取房产
    async getProperty(id) {
      this.repOk = true
      this.propertyList = await getPropertyApi(id)
      if (!this.propertyList.category) {
        this.propertyList.category = {}
      }
      if (!this.propertyList.agent) {
        this.propertyList.agent = {}
      }
    },
    // 图片回显
    echoImage() {
      this.$refs.coverImage.fileList.push({ url: this.propertyList.image })
      this.propertyList.photos.forEach((item) => {
        this.$refs.photoImage.fileList.push({ url: item })
      })
    },
    // 移除标签
    handleClose(tag) {
      // console.log(tag)
      const index = this.propertyList.tags.indexOf(tag)
      this.propertyList.tags.splice(index, 1)
    },
    // 添加标签失焦时触发,
    handleInputConfirm() {
      if (this.tagValue) {
        if (!this.propertyList.tags.includes(this.tagValue)) {
          this.propertyList.tags.push(this.tagValue)
        } else {
          this.$message.warning('该类标签已添加过了')
        }
      }
      this.tagValue = ''
      this.inputVisible = false
    },
    // 添加标签
    showInput() {
      this.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },

    // 取消
    isCancel() {
      this.repOk = true
      this.$emit('update:isShowDislog', false)
      // this.$parent.isShowDislog = false
      this.$refs.from.resetFields()
      this.$refs.coverImage.fileList = []
      this.$refs.photoImage.fileList = []
      this.propertyList = {
        agent: {},
        category: {},
        title: '',
        tags: [],
        address: '',
        price: '',
        desc: '',
        content: '',
        image: '',
        photos: []
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.el-form-item{
  width: 90%;
}
 .el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
</style>
